package com.visikard.ui.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.MerchantLoginTask;
import com.visikard.item.MerchantAccountObj;
import com.visikard.item.VKregisterMerchantSession;
import com.visikard.system.Theme;
import com.visikard.ui.R;
import com.visikard.utility.Utils;

public class MerchantLoginActivity extends BaseFragmentActivity implements OnClickListener {

	private static final int MAX_LOGION_TRY_COUNT = 5;

	// control
	private TextView txtRegister;
	private TextView txtForgotPass;
	private EditText edtUserName;
	private EditText edtPassWord;
	private EditText medtEmail = null;
	private View lyRegisterVisikard;
	private TextView txtSignIn;

	private AlertDialog alert = null;

	private Context mContext;
	// count login fail time
	private int mFailCount;

	// Asynctask
	BaseTask mAsyncTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.vk_login_activity);

		mContext = this;
		mFailCount = 0;
		innitControl();
		showKeyboard(false);

		// read saved user's info
		upDateFromPreference();

		// check restored session and do login
		if (VKRegApplication.merchantAccountObj != null && !VKRegApplication.merchantAccountObj.getUsername().isEmpty()
				&& !VKRegApplication.merchantAccountObj.getPassword().isEmpty()) {
			edtUserName.setText(VKRegApplication.merchantAccountObj.getUsername());
			edtPassWord.setText(VKRegApplication.merchantAccountObj.getPassword());
			doLogin();
		}
		else {
			// fill dummy data for debugging
			if (VKRegApplication.IS_DEBUGGING) {
				edtUserName.setText("christopher.alford74@yahoo.com");
				edtPassWord.setText("123456");
			}
		}
	}

	private void upDateFromPreference() {
		VKregisterMerchantSession vksession = VKRegApplication.instance.restoreMerchantSession();
		if (vksession == null)
			return;

		MerchantAccountObj accountObj = new MerchantAccountObj();

		accountObj.setUsername(vksession.getUsername());
		accountObj.setPassword(vksession.getPassword());
		accountObj.setIdUsers(vksession.getUserId());
		accountObj.setMerchantName(vksession.getMerchantName());
		accountObj.setMerchantLogo(vksession.getMerchantLogo());
		accountObj.setAddress(vksession.getLocationAddress());
		accountObj.setIdKard(vksession.getKardId());

		VKRegApplication.merchantAccountObj = accountObj;
		VKRegApplication.uid = vksession.getUserId();
	}

	private void innitControl() {
		lyRegisterVisikard = findViewById(R.id.layout_main_register);
		lyRegisterVisikard.setOnClickListener(this);

		txtRegister = (TextView) findViewById(R.id.vk_register);
		txtRegister.setOnClickListener(this);

		txtForgotPass = (TextView) findViewById(R.id.rg_text_forgot_pass);
		txtForgotPass.setOnClickListener(this);

		txtSignIn = (TextView) findViewById(R.id.txt_sign_in);
		txtSignIn.setOnClickListener(this);

		edtUserName = (EditText) findViewById(R.id.rg_edit_text_user_name);
		edtUserName.setTypeface(Theme.getFontRegular());
		edtUserName.setCursorVisible(false);
		edtUserName.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				edtUserName.setCursorVisible(true);
				// edtUserName.setFocusable(true);
				showKeyboard(true);
				return false;
			}
		});
		edtUserName.setOnEditorActionListener(new TextView.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT) {
					edtPassWord.setCursorVisible(true);
					edtPassWord.setFocusable(true);
				}
				return false;
			}
		});

		edtPassWord = (EditText) findViewById(R.id.rg_edit_text_pass_word);
		edtPassWord.setTypeface(Theme.getFontRegular());
		edtPassWord.setCursorVisible(false);
		edtPassWord.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				edtPassWord.setCursorVisible(true);
				showKeyboard(true);
				return false;
			}
		});
		edtPassWord.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEND) {
					showKeyboard(false);
					doLogin();
				}
				return false;
			}
		});

	}

	private void doLogin() {
		// validate userinput
		if (edtUserName.getText().toString().isEmpty()) {
			Toast.makeText(MerchantLoginActivity.this, getString(R.string.login_field_missing_username),
					Toast.LENGTH_SHORT).show();
		}
		else if (edtPassWord.getText().toString().isEmpty()) {
			Toast.makeText(MerchantLoginActivity.this, getString(R.string.login_field_missing_password),
					Toast.LENGTH_SHORT).show();
		}
		else {
			// merchant login task
			mAsyncTask = new MerchantLoginTask(mHandler);
			mAsyncTask.execute(edtUserName.getText().toString(), edtPassWord.getText().toString());
		}
	}

	protected void showKeyboard(boolean show) {
		if (show)
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
		else
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	/**
	 * show password recovery note
	 */
	private void showRecoveryNote() {
		String message = getResources().getString(R.string.login_field_invalid_1);
		if (mFailCount > 1) {
			message = getResources().getString(R.string.login_field_invalid_2, new Object[] { mFailCount });
		}

		AlertDialog alert = new AlertDialog.Builder(MerchantLoginActivity.this)
				.setIcon(android.R.drawable.ic_dialog_info).setTitle(R.string.sorry_title).setMessage(message)
				.setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						showForgotPass();
					}
				}).setNegativeButton(R.string.button_no, null).create();

		alert.show();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case UIMessage.MSG_EMAIL_INVALID:
				alert = new AlertDialog.Builder(mContext).setIcon(android.R.drawable.ic_dialog_info).setTitle("Login")
						.setMessage("Sorry, we need a valid email address.  Please try again")
						.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								showForgotPass();
							}
						}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						}).create();
				break;

			case UIMessage.MSG_EXIT_APP:
				alert = new AlertDialog.Builder(mContext).setIcon(android.R.drawable.ic_dialog_info).setTitle("Exit")
						.setMessage("Do you want exit application")
						.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								MerchantLoginActivity.this.finish();
							}
						}).setNegativeButton(android.R.string.cancel, null).create();
				break;

		}
		return alert;
	}

	private void showForgotPass() {
		Intent mIntent = new Intent(this, SendEmailRecoveryPass.class);
		if (edtUserName.getText() != null && !edtUserName.getText().toString().isEmpty()) {
			mIntent.putExtra(SendEmailRecoveryPass.KEY_EMAIL, edtUserName.getText().toString());
		}
		startActivity(mIntent);
		overridePendingTransition(R.anim.anim_slide_in_from_right, R.anim.anim_slide_out_from_right);
	}

	private void doLoginSuccess(MerchantAccountObj accountObj) {

		VKRegApplication.uid = accountObj.getIdUsers();
		VKRegApplication.merchantAccountObj = accountObj;

		// overwrite password
		VKRegApplication.merchantAccountObj.setPassword(edtPassWord.getText().toString());

		VKregisterMerchantSession vksession = new VKregisterMerchantSession();
		vksession.setUsername(VKRegApplication.merchantAccountObj.getUsername());
		vksession.setPassword(VKRegApplication.merchantAccountObj.getPassword());
		vksession.setUserId(VKRegApplication.uid);
		vksession.setLoginSession(VKRegApplication.loginSession);
		vksession.setKardId(VKRegApplication.merchantAccountObj.getIdKard());
		vksession.setMerchantLogo(VKRegApplication.merchantAccountObj.getMerchantLogo());
		vksession.setMerchantName(VKRegApplication.merchantAccountObj.getMerchantName());
		VKRegApplication.instance.saveMerchantSession(vksession);

		if (VKRegApplication.IS_TESTING) {
			Intent intent = new Intent(MerchantLoginActivity.this, TestActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
			return;
		}

		// Start Home activity
		Intent intent = new Intent(MerchantLoginActivity.this, MerchantHomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm;
		switch (v.getId()) {
			case R.id.vk_register:
				imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(lyRegisterVisikard.getWindowToken(), 0);

				break;
			case R.id.rg_text_forgot_pass:
				imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(lyRegisterVisikard.getWindowToken(), 0);

				showForgotPass();
				break;

			case R.id.layout_main_register:
				imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(lyRegisterVisikard.getWindowToken(), 0);
				break;

			case R.id.txt_sign_in:
				showKeyboard(false);
				doLogin();
				break;

			default:
				break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_visikard_register_activity, menu);
		return true;
	}

	// Handle message method
	@SuppressWarnings("deprecation")
	@Override
	protected boolean handleMessage(Message msg) {
		switch (msg.what) {
			case UIMessage.MSG_LOGIN_SUCCESS:
				if (msg.obj != null && msg.obj instanceof MerchantAccountObj) {
					doLoginSuccess((MerchantAccountObj) msg.obj);
				}
				return true;
			case UIMessage.MSG_WRONG_USERNAME_PASSWORD:
				if (mFailCount < MAX_LOGION_TRY_COUNT) {
					mFailCount++;
					showRecoveryNote();
				}
				else {
					MerchantLoginActivity.this.finish();
				}
				return true;
			case UIMessage.MSG_NOT_VALIDATE_EMAIL:
				Toast.makeText(mContext, "Sorry, we need a valid email address. Please try again", Toast.LENGTH_SHORT)
						.show();
				medtEmail.setTextColor(Color.parseColor("#000000"));
				return true;
			case UIMessage.MSG_SEND_MAIL_SUCCESS:
				alert = new AlertDialog.Builder(mContext)
						.setIcon(android.R.drawable.ic_dialog_info)
						.setTitle("Login")
						.setMessage(
								"OK, we've sent the password to your email.  Please check your email, then try logging in.")
						.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						}).create();
				alert.show();
				return true;
			case UIMessage.MSG_EMAIL_INVALID:
				mHandler.sendEmptyMessage(UIMessage.MSG_DISMISS_DIALOG);
				showDialog(UIMessage.MSG_EMAIL_INVALID);
				return true;
			case UIMessage.MSG_LOGIN_INCOMPLETE:
				Utils.showToast(getApplicationContext(), R.string.login_field_missing);
				return true;
		}
		return super.handleMessage(msg);
	}
}
